package com.itheima.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.Utils.JwtUtils;
import com.itheima.dto.LoginDto;
import com.itheima.ex.CustomerException;
import com.itheima.mapper.EmpExprMapper;
import com.itheima.mapper.EmpMapper;
import com.itheima.pojo.*;
import com.itheima.service.EmpLogService;
import com.itheima.service.EmpService;
import com.itheima.vo.LoginVo;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 员工业务层
 *
 * @author GY
 * @version V1.0
 * @date 2025-01-12 9:05
 */
@Service
@RequiredArgsConstructor
public class EmpServiceImpl implements EmpService {

    private final EmpMapper empMapper;
    private final EmpExprMapper empExprMapper;
    private final EmpLogService empLogService;

    @Override
    public PageResult<Emp> pageQuery(EmpQueryParam empQueryParam) {
        // 设置分页参数
        PageHelper.startPage(empQueryParam.getPage(), empQueryParam.getPageSize());
        // List<Emp> emps = empMapper.findPage();
        List<Emp> emps = empMapper.findPage(empQueryParam);
        // 获取分页结果
        Page<Emp> p = (Page<Emp>) emps;
        return new PageResult<>(p.getTotal(), p.getResult());
    }

    @Override
    @Transactional(rollbackFor = {Exception.class})
    public void saveAndExprList(Emp emp) {
        try {
            emp.setPassword("123456");
            emp.setCreateTime(LocalDateTime.now());
            emp.setUpdateTime(LocalDateTime.now());

            empMapper.insert(emp);
            // 保存员工工作经历

            List<EmpExpr> exprList = emp.getExprList();

            exprList.forEach(v -> v.setEmpId(emp.getId()));

            if (!exprList.isEmpty()) {
                empExprMapper.batchSave(exprList);
            }
        } finally {
            // 记录操作日志
            EmpLog empLog = new EmpLog(null, LocalDateTime.now(), emp.toString());
            empLogService.insertLog(empLog);


        }

    }

    @Override
    public List<Emp> findAll(Emp emp) {
        List<Emp> e = empMapper.findAll();
        return e;
    }

    @Override
    @Transactional(rollbackFor = {Exception.class})
    public void deleteByIds(List<Integer> ids) {
        // 1.参数校验
        if (ObjectUtils.isEmpty(ids)) {
            throw new RuntimeException("非法参数异常:员工ID列表为空");
        }
        // 2.删除员工
        empMapper.deleteByIds(ids);
        // 3.删除员工对应的工作经历
        empExprMapper.deleteByExprIds(ids);
    }

    @Override
    public Emp findByIdAndExprList(Integer id) {
        return empMapper.findByIdAndExprList(id);
    }

    @Override
    @Transactional(rollbackFor = {Exception.class})
    public void updateEmpAndExprList(Emp emp) {
        // 1.更改员工信息
        emp.setUpdateTime(LocalDateTime.now());
        empMapper.updateEmp(emp);
        // 2.删除员工经历
        empExprMapper.deleteByExprIds(Arrays.asList(emp.getId()));
        // 3.新增员工经历
        Integer empId = emp.getId();
        List<EmpExpr> exprList = emp.getExprList();
        if (!exprList.isEmpty()) {
            exprList.forEach(o -> o.setEmpId(empId));
            empExprMapper.batchSave(exprList);
        }
    }

    @Override
    public LoginVo login(LoginDto loginDto) {
        //1.参数校验
        if (ObjectUtils.isEmpty(loginDto)
            ||StringUtils.isEmpty(loginDto.getUsername())
            || StringUtils.isEmpty(loginDto.getPassword())){
            throw new CustomerException("用户名或密码为空,请重新输入!");
        }
        // 2.业务操作
        Emp emp = empMapper.selectByUser(loginDto.getUsername());
        if (ObjectUtils.isEmpty(emp)){
            throw new CustomerException("用户名不存在,请重新输入!");
        }
        if (!StringUtils.equals(loginDto.getPassword(),emp.getPassword())){
            throw new CustomerException("用户名或密码有误,请重新输入!");
        }
        //3.数据封装
        LoginVo loginVo = new LoginVo();
        BeanUtils.copyProperties(emp,loginVo);
        loginVo.setId(emp.getId());
        loginVo.setUsername(emp.getUsername());
        loginVo.setName(emp.getName());
        //token
        Map<String, Object> claims = new HashMap<>();
        claims.put("id",loginVo.getId());
        claims.put("username",loginVo.getUsername());
        String token = JwtUtils.generateJwt(claims);
        loginVo.setToken(token);
        return loginVo;
    }
}
